import '@babel/register';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { ENV, ROOT, USER_STORE, getSessionConfig, init } from '@sker/core'
import { container } from 'tsyringe';
import { join } from 'path';
import { ExpressAdapter } from '@nestjs/platform-express'
import { readFileSync } from 'fs-extra';
import { compile } from 'art-template'
import session from 'express-session';

async function bootstrap() {
    const parsedArgs = init()
    const adapter = new ExpressAdapter();
    const root = container.resolve(ROOT)
    await NestFactory.create(AppModule, adapter, {
        cors: true,
        bodyParser: true,
    }).then(async app => {
        const { port, host } = parsedArgs;
        const env = container.resolve(ENV)
        const isDev = !!env.dev
        adapter.useStaticAssets(join(root, 'public'), {})
        adapter.useStaticAssets(join(root, 'public/docs'), {})
        adapter.useStaticAssets(join(root, 'attachments'), {})
        adapter.useStaticAssets(join(root, 'addons'), {})
        adapter.setViewEngine('art-template')
        adapter.engine('html', (path: any, options: any, callback: any) => {
            try {
                if (!isDev && container.isRegistered(path)) {
                    const render = container.resolve<any>(path);
                    const html = render(options);
                    callback(null, html)
                    return;
                }
                const content = readFileSync(path, 'utf-8')
                const render = compile(content)
                container.register(path, { useValue: render })
                const html = render(options);
                callback(null, html)
                return;
            } catch (e) {
                callback(e)
            }
        })
        const sessionConfig = getSessionConfig(container)
        container.register(USER_STORE, { useValue: sessionConfig.store })
        app.use(require('cookie-parser')())
        app.use(session(sessionConfig))
        await app.listen(port, host)
        Logger.log(`http:${host}:${port}/graphql`);
    }).catch(e => {
        Logger.error(e.message)
    });
}
bootstrap().catch();
